package com.techsoul.module.tms.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.constant.ApiConstants;
import com.techsoul.common.core.exception.BusinessException;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.basic.mapper.TBmLocationMapper;
import com.techsoul.module.basic.pojo.param.WarehouseSaveParam;
import com.techsoul.module.basic.pojo.vo.TBmLocationVo;
import com.techsoul.module.basic.pojo.vo.WarehouseVo;
import com.techsoul.module.basic.service.IWarehouseService;
import com.techsoul.module.order.mapper.PurchaseOrderItemMapper;
import com.techsoul.module.order.mapper.PurchaseOrderMapper;
import com.techsoul.module.order.pojo.entity.PurchaseOrder;
import com.techsoul.module.order.pojo.entity.PurchaseOrderItem;
import com.techsoul.module.order.pojo.vo.PurchaseOrderVo;
import com.techsoul.module.pms.enmus.FreightVehicleDispatchStatusEnum;
import com.techsoul.module.pms.enmus.TransportationTypeEnum;
import com.techsoul.module.pms.mapper.TbWmsMaterialDeliveryLineMapper;
import com.techsoul.module.pms.pojo.entity.TbWmsMaterialReceiptNotExist;
import com.techsoul.module.pms.pojo.param.TWhWarehouseCustomerMaterialSaveParam;
import com.techsoul.module.pms.pojo.vo.TWhWarehouseCustomerMaterialVo;
import com.techsoul.module.pms.pojo.vo.TbWmsMaterialDeliveryLineVo;
import com.techsoul.module.pms.pojo.vo.TbWmsMaterialDeliveryVo;
import com.techsoul.module.pms.service.ITWhWarehouseCustomerMaterialService;
import com.techsoul.module.tms.mapper.*;
import com.techsoul.module.tms.pojo.entity.*;
import com.techsoul.module.tms.pojo.param.CarrierSearchParam;
import com.techsoul.module.tms.pojo.param.DriverSearchParam;
import com.techsoul.module.tms.pojo.param.ExpressSaveParam;
import com.techsoul.module.tms.pojo.param.ExpressSearchParam;
import com.techsoul.module.tms.pojo.vo.DispatchImportOrderItemVo;
import com.techsoul.module.tms.pojo.vo.DriverVo;
import com.techsoul.module.tms.pojo.vo.ExpressVo;
import com.techsoul.module.tms.service.IExpressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.techsoul.module.tms.pojo.vo.CarrierVo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 物流信息 Service实现
 *
 * @author liuen
 * @date 2021-01-26
 */
@DS("tms")
@Service
@Slf4j
@Transactional(readOnly = true)
public class ExpressServiceImpl implements IExpressService {

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private CarrierMapper carrierMapper;
    @Autowired
    private ExpressMapper mapper;
    @Autowired
    private TFoFreightOrderMapper tFoFreightOrderMapper;


    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private PurchaseOrderItemMapper purchaseOrderItemMapper;
    @Autowired
    private TPoPurchaseOrderMapper tPoPurchaseOrderMapper;

    @Autowired
    private TBmLocationMapper locationmapper;
    @Autowired
    private FreightVehicleAssignedMapper fsmapper;
    @Autowired
    private TFoFreightOrderItemMapper tFoFreightOrderItemMapper;
    @Autowired
    private TbWmsMaterialDeliveryLineMapper tbWmsMaterialDeliveryLineMapper;
    @Autowired
    private FreightVehicleDispatchMapper freightVehicleDispatchMapper;
    @Autowired
    private FreightVehicleAssignedLineMapper feightVehicleAssignedLineMapper;
    @Autowired
    private TsCarrierServiceImpl tsCarrierServiceImpl;
    @Autowired
    private IWarehouseService warehouseService ;

    @Autowired
    private ITWhWarehouseCustomerMaterialService tWhWarehouseCustomerMaterialService;
    @Autowired
    private FreightVehicleDistributionMapper freightVehicleDistributionMapper;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private iCustomerMapper customerMapper;

    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(ExpressSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        Express entity = new Express();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.mapper.insert(entity);
        return entity.getId();
    }
    @Transactional(readOnly = false)
    @Override
    public void genPurchaseOrderAndItem(PurchaseOrder order, PurchaseOrderItem item){
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

        order.setId(idWorker.nextId() + "").preInsert(user.getId());;

        this.purchaseOrderMapper.insert(order);

        item.setPurchaseOrderId(order.getId());
        item.setId(idWorker.nextId() + "").preInsert(user.getId());

        this.purchaseOrderItemMapper.insert(item);
    }

    @Transactional(readOnly = false)
    @Override
    public void genPurchaseOrderAndItem(PurchaseOrder order, PurchaseOrderItem item, TbWmsMaterialDeliveryLineVo tbWmsMaterialDeliveryLineVo){
        PurchaseOrderVo vo = this.purchaseOrderMapper.findBySourceOrderIdAndIsValid(tbWmsMaterialDeliveryLineVo.getId());
        PurchaseOrder entity = new PurchaseOrder();
        BeanUtils.copyProperties(vo, entity);
        entity.setIsValid("1");
        this.purchaseOrderMapper.updateById(entity);
    }
    @Transactional(readOnly = false)
    @Override
    public void createDispatch(TFoFreightOrder order,  TFoFreightOrderItem item){
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

    }

    @Transactional(readOnly = false)
    @Override
    public void createCustomer(iCustomer customer){
        customerMapper.insert(customer);
    }

    @Override
    public iCustomer selectByCustomerId(String customerId){
        return customerMapper.selectById(customerId);
    }

    @Transactional(readOnly = false)
    @Override
    public void genFreightOrderAndItem(TFoFreightOrder order,  TFoFreightOrderItem item){
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String Wmsid = "WMS".concat(String.valueOf(idWorker.nextId()));

        order.setId(Wmsid).preInsert(user.getId());

        this.tFoFreightOrderMapper.insert(order);

        String Wmsitemid = "WMS".concat(String.valueOf(idWorker.nextId()));
        item.setId(Wmsid).preInsert(user.getId());

        this.tFoFreightOrderItemMapper.insert(item);
    }
    @Transactional(readOnly = false)
    @Override
    public void genFreightOrderAndItem(List<TFoFreightOrder> orders, List<TFoFreightOrderItem> items, List<String> driverNos, String carrierNo, String frwarehouse, String tow,String routeType){
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        TBmLocationVo departloc =new TBmLocationVo();
        TBmLocationVo destloc =new TBmLocationVo();
        for(int i=0; i<orders.size();i++){
            String Wmsid = "WMS".concat(String.valueOf(idWorker.nextId()));
            TFoFreightOrder order = (TFoFreightOrder)orders.get(i);
            order.setId(Wmsid).preInsert(user.getId());

            if(order.getFreightOrderNo()==null || order.getFreightOrderNo().length()<=0){
                String s = "L".concat(String.valueOf(idWorker.nextId()));
                order.setFreightOrderNo(s);
                order.setStatus("CREATED");
            }

            this.tFoFreightOrderMapper.insert(order);

            if(i==0){
                departloc = this.locationmapper.findByTreeId(order.getDeparture());
                destloc = this.locationmapper.findByTreeId(order.getDestination());
            }
        }
        for(int j=0;j<items.size();j++){
            TFoFreightOrderItem item = (TFoFreightOrderItem)items.get(j);
            String Wmsitemid = "WMS".concat(String.valueOf(idWorker.nextId()));
            String Wmsid = "WMS".concat(String.valueOf(idWorker.nextId()));
            item.setId(Wmsid).preInsert(user.getId());
            this.tFoFreightOrderItemMapper.insert(item);
        }



        String rt =this.createVehicleRelocateDispatch
                ( driverNos,items,user,departloc,destloc,carrierNo,frwarehouse, tow,routeType);
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(ExpressSaveParam params) {
        Express entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public ExpressVo findById(String id) {
        return this.mapper.findById(id);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<ExpressVo> findAll(ExpressSearchParam params) {
        return this.mapper.findAll(params);
    }

    @Override
    public IPage<DriverVo> driverSearch(DriverSearchParam params, Integer current, Integer pageSize) {
        return this.driverMapper.driverSearch(new Page<>(current, pageSize), params);
    }

    @Override
    public List<DriverVo> driverFindAll(DriverSearchParam params) {
        return this.driverMapper.findAll(params);
    }
    @Override
    public List<CarrierVo> carrierFindAll(CarrierSearchParam params) {
        return this.tsCarrierServiceImpl.findAll(params);
    }
    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<ExpressVo> findAll(ExpressSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }

    @Transactional(readOnly = false)   //移库和转场调度
    public  String callDriver(FreightVehicleDispatch freightVehicleDispatch,
                              List<FreightVehicleDistribution>  distributs, String mobile, TBmLocationVo departloc,
                              TBmLocationVo destloc,UserVo userVo ){
        FreightVehicleAssigned assign = new FreightVehicleAssigned();
        double wt=0;double vol = 0;
        String type = "";


        // String location=freightVehicleDispatch.getShipmentLocation().split("-")[0];
        //String sublocation=freightVehicleDispatch.getShipmentLocation().split("-")[1];

        assign.setDepartureName(departloc.getTreeNames());
        assign.setDestinationName(destloc.getTreeNames());
        assign.setOrderNo(freightVehicleDispatch.getFreightOrderNo());
        //assign.setPickupAddr(freightVehicleDispatch.getPickUpAdd());
        assign.setPickupAddr(freightVehicleDispatch.getPickupAddress());
        assign.setLoadMethod(freightVehicleDispatch.getLoadMethod());
        assign.setDeliveryCity(freightVehicleDispatch.getDestination());
        assign.setDeliveryLatitude(destloc.getLatitude());
        assign.setDepartCity(freightVehicleDispatch.getShipmentLocation());
        assign.setDepartLatitude(departloc.getLatitude());
        //assign.setDeliveryAddr(freightVehicleDispatch.getDropOffAdd());
        assign.setDeliveryAddr(freightVehicleDispatch.getDeliveryAddress());
        assign.setCustomerNo(freightVehicleDispatch.getSite());
        assign.setDeliveryLongitude(destloc.getLongitude());
        assign.setDepartLongitude(departloc.getLongitude());
        if(freightVehicleDispatch.getExecuteDate()!=null){
            assign.setEstPickupTime
                    (DateUtils.getDateStrSplitWithTm(freightVehicleDispatch.getExecuteDate()));

        }else{
            assign.setEstPickupTime
                    (DateUtils.getDateStrSplitWithTm(new Date()));

        }
        assign.setFtlOrLtl("F");
        assign.setDispatchId(freightVehicleDispatch.getId());
        //	assign.setDistributionNo(String.valueOf(trbution.getDistributionId()));

        //旧状态，在司机APP上无法查到
        //assign.setStatus(FreightVehicleAssignedStatusEnum.CREATED.getStatusCode());
        //在司机APP上以这个状态进行查询
        assign.setStatus("initial");
        if(freightVehicleDispatch.getPublishDriverPrice()!=null){
            assign.setPriceOffer(new BigDecimal(freightVehicleDispatch.getPublishDriverPrice()));
        }


        if(freightVehicleDispatch.getAccountPayable()!=null){
            assign.setPriceAmtTot(freightVehicleDispatch.getAccountPayable());
        }
        assign.setCarrierNo(freightVehicleDispatch.getCarrierNo());
        assign.setCarrier(freightVehicleDispatch.getCarrierName());
        assign.setEstDeliveryDay(freightVehicleDispatch.getPlanDate());
        assign.setCustomerNo(freightVehicleDispatch.getCustomerNo());
        assign.setCustomerName(freightVehicleDispatch.getCustomerName());
        assign.setConsigneeName(freightVehicleDispatch.getConsigneeName());
        assign.setConsigneeid(freightVehicleDispatch.getConsigneeNo());
        assign.setConsigneeMobilePhone(freightVehicleDispatch.getConsigneePhone());
        assign.setTotTonWeight(freightVehicleDispatch.getTotWeight());
        assign.setConsigneeAddress(freightVehicleDispatch.getDropOffAdd());
        assign.setSite(freightVehicleDispatch.getSite());
        assign.setSendDrivers(mobile);
        assign.setDriverMobile(mobile);
        assign.setRouteDistanceType("local");
        assign.setIsBidden(false);
        assign.setLoadMethod(freightVehicleDispatch.getLoadMethod());
        assign.setIsSelfDriver(false);
        assign.setId(idWorker.nextId() + "")
                .preInsert(userVo.getId());
        assign.setAssignSeq(assign.getId());
        assign.setIsValid("1");

        String assignid= assign.getId();
        this.fsmapper.insert(assign);


        for(int u =0; u <distributs.size();u++){
            FreightVehicleDistribution trbution =
                    (FreightVehicleDistribution)distributs.get(u);
            FreightVehicleAssignedLine nextassignline = new FreightVehicleAssignedLine();
            nextassignline.setWeight(trbution.getWeight());
            nextassignline.setDistributionNo(trbution.getId());
            nextassignline.setOrderNo(trbution.getOrderSource());
            nextassignline.setRouteDistanceType("local");
            nextassignline.setAssignLineSeq(trbution.getContainerNo());// 入库单明细号
            nextassignline.setTargetWarehouseDeliveryLineNo(trbution.getCauseNo());// 出库单明细号
            nextassignline.setVolume(trbution.getVolume());
            nextassignline.setCargoType(trbution.getCargoFreightName());
            nextassignline.setAssignSeq(assignid);
            nextassignline.setPackQty(trbution.getPackQty());
            nextassignline.setCustShippedQty(trbution.getWeight());
            nextassignline.setCustShippedQtyUnit(trbution.getWeightMeasUnit());
            nextassignline.setQuantity(trbution.getQuantity());
            nextassignline.setWeightUnit(trbution.getWeightMeasUnit());
            nextassignline.setVolUnit(trbution.getVolumeMeasUnit());
            nextassignline.setFreightOrderNo(trbution.getFreightOrderNo());
            nextassignline.setSite(assign.getSite());
            nextassignline.setAssignLineSeq(String.valueOf(u));
            nextassignline.setDepartLoc(trbution.getShipmentLocation());
            nextassignline.setDeliveryAddr(trbution.getDeliveryAddr());
            nextassignline.setDeliveryLoc(trbution.getDestination());
            nextassignline.setPickupAddress(trbution.getPickupAddress());
            nextassignline.setId(idWorker.nextId() + "")
                    .preInsert(userVo.getId());
            nextassignline.setIsValid("1");

            this.feightVehicleAssignedLineMapper.insert(nextassignline);

        }

        return "success";
    }
    @Transactional(readOnly = false)   //移库和转场调度
    public String createVehicleRelocateDispatch
            (List<String> senddriver, List<TFoFreightOrderItem> dispatchItems, UserVo userVo,TBmLocationVo depart ,TBmLocationVo dest,
             String carrierNo,String fr, String toW,String routeType){
        List dynamicDriversList = new ArrayList<String>();
        if(senddriver!=null&&senddriver.size()>0){
            dynamicDriversList.addAll(senddriver);
        }

        if(!StringUtils.isNull(carrierNo)){
            Carrier driver = this.carrierMapper.selectById(carrierNo);
            for(int i=0;i<dispatchItems.size();i++) {
                TFoFreightOrderItem freightOrderItem = (TFoFreightOrderItem) dispatchItems.get(i);
                FreightVehicleDispatch freightVehicleDispatch = new FreightVehicleDispatch();



                TFoFreightOrderItem fstfreightOrderItem = (TFoFreightOrderItem) dispatchItems.get(0);
                // freightVehicleDispatch.setCarrierName(driver.get());
                freightVehicleDispatch.setCarrierNo(driver.getId());
                freightVehicleDispatch.setCarrierName(driver.getCarrierName());
                freightVehicleDispatch.setCarrierSite(driver.getCarrierSite());
                freightVehicleDispatch.setVehicleIdentity(freightOrderItem.getVinNo());
                freightVehicleDispatch.setVehicleModel(freightOrderItem.getVehicleModel());
                freightVehicleDispatch.setVehicleNo(freightOrderItem.getVehicleName());
                freightVehicleDispatch.setVehicleType(freightOrderItem.getVehicleLoadType());
                freightVehicleDispatch.setDriver("");
                freightVehicleDispatch.setDriverName("");
                freightVehicleDispatch.setPlanDate(fstfreightOrderItem.getEstDeliveryDate());
                freightVehicleDispatch.setExecuteDate(fstfreightOrderItem.getEstDepartTm());
                freightVehicleDispatch.setEstDeliveryDate(fstfreightOrderItem.getEstDeliveryDate());
                freightVehicleDispatch.setEstPickupDate(fstfreightOrderItem.getEstDepartTm());
                freightVehicleDispatch.setDriverPhone(driver.getContactMobile());
                freightVehicleDispatch.setJobType(TransportationTypeEnum.changeWarehouse.getStatusCode());
                freightVehicleDispatch.setShipmentLocation(fstfreightOrderItem.getDeparture());
                freightVehicleDispatch.setDeliveryAddress(fstfreightOrderItem.getDestinationAddr());
                freightVehicleDispatch.setPickupAddress(fstfreightOrderItem.getDepartureAddr());
                freightVehicleDispatch.setRouteDistanceType("local");
                freightVehicleDispatch.setSelfDriverYn("N");
                freightVehicleDispatch.setDispatchTime(new Date());
                freightVehicleDispatch.setPickupCity(fr);
                freightVehicleDispatch.setDeliveryCity(toW);
                freightVehicleDispatch.setShipmentLocation(depart.getTreeIds());
                freightVehicleDispatch.setDestination(dest.getTreeIds());
                freightVehicleDispatch.preInsert(userVo.getId());
                freightVehicleDispatch.setIsValid("1");
                freightVehicleDispatch.setRouteType(routeType);
                freightVehicleDispatch.setId(idWorker.nextId() + "")
                        .preInsert(userVo.getId());
                freightVehicleDispatch.setDispatchNo(freightVehicleDispatch.getId().concat("-").concat(fstfreightOrderItem.getFreightOrderNo()));
                this.freightVehicleDispatchMapper.insert(freightVehicleDispatch);

                List<FreightVehicleDistribution> freightVehicleDistributions = new ArrayList<FreightVehicleDistribution>();


                FreightVehicleDistribution freightVehicleDistribution = new FreightVehicleDistribution();
                org.springframework.beans.BeanUtils.copyProperties(freightOrderItem, freightVehicleDistribution);
                freightVehicleDistribution.setVehicleId(fstfreightOrderItem.getVinNo());
                freightVehicleDistribution.setVehicleNo(fstfreightOrderItem.getVehicleName());
                freightVehicleDistribution.setDispatchId(freightVehicleDispatch.getId());
                freightVehicleDistribution.setStatus(FreightVehicleDispatchStatusEnum.CREATED.getStatusCode());
                freightVehicleDistribution.setCarrierNo(driver.getId());
                freightVehicleDistribution.setCarrierName(driver.getCarrierName());
                freightVehicleDistribution.setDriver(driver.getId());
                freightVehicleDistribution.setDriverName("");
                freightVehicleDistribution.setDriverMobile("");
                freightVehicleDistribution.setShipmentLocation(freightOrderItem.getDeparture());
                freightVehicleDistribution.setDeliveryAddress(freightOrderItem.getDestinationAddr());
                freightVehicleDistribution.setPickupAddress(freightOrderItem.getDepartureAddr());
                freightVehicleDistribution.setEstDeliveryDate(freightOrderItem.getEstDeliveryDate());
                freightVehicleDistribution.setCargoFreightType(freightOrderItem.getCargoFreightType());
                freightVehicleDistribution.setCargoFreightSpec(freightOrderItem.getCargoFreightSpec());
                freightVehicleDistribution.setCargoFreightName(freightOrderItem.getCargoFreightName());
                freightVehicleDistribution.setCargoFreightNo(freightOrderItem.getCargoFreightNo());
                freightVehicleDistribution.setCarrierSettleBasedOn("FTL");
                freightVehicleDistribution.setConsigneeName(freightOrderItem.getConsigneeName());
                freightVehicleDistribution.setConsigeeContactNo(freightOrderItem.getConsigneePhone());
                freightVehicleDistribution.setQuantity(new BigDecimal(1));
                freightVehicleDistribution.setOrderSource(freightOrderItem.getOrderFromSource());
                freightVehicleDistribution.setPickUpWarehouseNo(freightOrderItem.getWarehouseCd());
                freightVehicleDistribution.setDropOffWarehouseNo(freightOrderItem.getDropOffWarehouseNo());
                freightVehicleDistribution.setRouteDistanceType("local");
                freightVehicleDistribution.setCauseNo(freightOrderItem.getCauseNo()); // 出库单明细号
                freightVehicleDistribution.setContainerNo(freightOrderItem.getContainerNo()); // 入库单明细号

                freightVehicleDistribution.setPickupAddress(freightOrderItem.getDepartureAddr());
                freightVehicleDistribution.setDeliveryAddress(freightOrderItem.getConsigneeAddress());

                freightVehicleDistribution.setId(idWorker.nextId() + "")
                        .preInsert(userVo.getId());
                freightVehicleDistribution.setIsValid("1");
                this.freightVehicleDistributionMapper.insert(freightVehicleDistribution);
                freightVehicleDistributions.add(freightVehicleDistribution);
                String rt = this.callDriver(freightVehicleDispatch, freightVehicleDistributions, driver.getContactMobile(),
                        depart,dest,userVo);
                if(!rt.equals("success")){
                    throw new BusinessException(rt);
                }

            }


            return "success";
        }
        for(int i=0;i<dispatchItems.size();i++) {
            TFoFreightOrderItem freightOrderItem = (TFoFreightOrderItem) dispatchItems.get(i);
            FreightVehicleDispatch freightVehicleDispatch = new FreightVehicleDispatch();
            String senddriverid ="";


            if(dynamicDriversList.size()>i){
                senddriverid = (String)dynamicDriversList.get(i);
            }else{ //重复使用司机
                dynamicDriversList.addAll(senddriver);
                senddriverid = (String)dynamicDriversList.get(i);
            }

            Driver driver = this.driverMapper.findById(senddriverid);
            TFoFreightOrderItem fstfreightOrderItem = (TFoFreightOrderItem) dispatchItems.get(0);
            // freightVehicleDispatch.setCarrierName(driver.get());
            freightVehicleDispatch.setCarrierNo(driver.getCompanyNo());
            freightVehicleDispatch.setCarrierSite(driver.getCompanyNo());
            freightVehicleDispatch.setVehicleIdentity(freightOrderItem.getVinNo());
            freightVehicleDispatch.setVehicleModel(freightOrderItem.getVehicleModel());
            freightVehicleDispatch.setVehicleNo(freightOrderItem.getVehicleName());
            freightVehicleDispatch.setVehicleType(freightOrderItem.getVehicleLoadType());
            freightVehicleDispatch.setDriver(driver.getDriverNo());
            freightVehicleDispatch.setDriverName(driver.getPersonName());
            freightVehicleDispatch.setPlanDate(fstfreightOrderItem.getEstDeliveryDate());
            freightVehicleDispatch.setExecuteDate(fstfreightOrderItem.getEstDepartTm());
            freightVehicleDispatch.setEstDeliveryDate(fstfreightOrderItem.getEstDeliveryDate());
            freightVehicleDispatch.setEstPickupDate(fstfreightOrderItem.getEstDepartTm());
            freightVehicleDispatch.setDriverPhone(driver.getMobile());
            freightVehicleDispatch.setJobType(TransportationTypeEnum.changeWarehouse.getStatusCode());
            freightVehicleDispatch.setShipmentLocation(fstfreightOrderItem.getDeparture());
            freightVehicleDispatch.setDeliveryAddress(fstfreightOrderItem.getDestinationAddr());
            freightVehicleDispatch.setPickupAddress(fstfreightOrderItem.getDepartureAddr());
            freightVehicleDispatch.setDispatchTime(new Date());
            freightVehicleDispatch.setRouteDistanceType("local");
            freightVehicleDispatch.setSelfDriverYn("Y");
            freightVehicleDispatch.setStatus(FreightVehicleDispatchStatusEnum.CREATED.getStatusCode());
            freightVehicleDispatch.setPickupCity(fr);
            freightVehicleDispatch.setDeliveryCity(toW);
            freightVehicleDispatch.setShipmentLocation(depart.getTreeIds());
            freightVehicleDispatch.setDestination(dest.getTreeIds());
            String zone = ((TFoFreightOrderItem) dispatchItems.get(0)).getDestZone();

            freightVehicleDispatch.setId(idWorker.nextId() + "")
                    .preInsert(userVo.getId());
            freightVehicleDispatch.setIsValid("1");
            freightVehicleDispatch.setDispatchNo(freightVehicleDispatch.getId().concat("-").concat(fstfreightOrderItem.getFreightOrderNo()));
            this.freightVehicleDispatchMapper.insert(freightVehicleDispatch);

            List<FreightVehicleDistribution> freightVehicleDistributions = new ArrayList<FreightVehicleDistribution>();


            FreightVehicleDistribution freightVehicleDistribution = new FreightVehicleDistribution();
            org.springframework.beans.BeanUtils.copyProperties(freightOrderItem, freightVehicleDistribution);
            freightVehicleDistribution.setVehicleId(fstfreightOrderItem.getVinNo());
            freightVehicleDistribution.setVehicleNo(fstfreightOrderItem.getVehicleName());
            freightVehicleDistribution.setDispatchId(freightVehicleDispatch.getId());
            freightVehicleDistribution.setStatus(FreightVehicleDispatchStatusEnum.CREATED.getStatusCode());
            freightVehicleDistribution.setCarrierNo(driver.getCompanyNo());
            freightVehicleDistribution.setCarrierName(driver.getPersonName());
            freightVehicleDistribution.setDriver(driver.getId());
            freightVehicleDistribution.setDriverName(driver.getPersonName());
            freightVehicleDistribution.setDriverMobile(driver.getMobile());
            freightVehicleDistribution.setShipmentLocation(freightOrderItem.getDeparture());
            freightVehicleDistribution.setDeliveryAddress(freightOrderItem.getDestinationAddr());
            freightVehicleDistribution.setPickupAddress(freightOrderItem.getDepartureAddr());
            freightVehicleDistribution.setEstDeliveryDate(freightOrderItem.getEstDeliveryDate());
            freightVehicleDistribution.setCargoFreightType(freightOrderItem.getCargoFreightType());
            freightVehicleDistribution.setCargoFreightSpec(freightOrderItem.getCargoFreightSpec());
            freightVehicleDistribution.setCargoFreightName(freightOrderItem.getCargoFreightName());
            freightVehicleDistribution.setCargoFreightNo(freightOrderItem.getCargoFreightNo());
            freightVehicleDistribution.setCarrierSettleBasedOn("FTL");
            freightVehicleDistribution.setConsigneeName(freightOrderItem.getConsigneeName());
            freightVehicleDistribution.setConsigeeContactNo(freightOrderItem.getConsigneePhone());
            freightVehicleDistribution.setQuantity(new BigDecimal(1));
            freightVehicleDistribution.setOrderSource(freightOrderItem.getOrderFromSource());
            freightVehicleDistribution.setPickUpWarehouseNo(freightOrderItem.getWarehouseCd());
            freightVehicleDistribution.setDropOffWarehouseNo(freightOrderItem.getDropOffWarehouseNo());
            freightVehicleDistribution.setRouteDistanceType("local");
            freightVehicleDistribution.setPickupAddress(freightOrderItem.getDepartureAddr());
         //   freightVehicleDistribution.setDeliveryAddress(freightOrderItem.getConsigneeAddress());
            freightVehicleDistribution.setId(idWorker.nextId() + "")
                    .preInsert(userVo.getId());
            freightVehicleDistribution.setIsValid("1");
            this.freightVehicleDistributionMapper.insert(freightVehicleDistribution);
            freightVehicleDistributions.add(freightVehicleDistribution);
            String rt = this.callDriver(freightVehicleDispatch, freightVehicleDistributions, driver.getMobile(),
                    depart,dest,userVo);
            if(!rt.equals("success")){
                throw new BusinessException(rt);
            }

        }

        return "success";
    }
    @Override
    @Transactional(readOnly = false)
    public void insertItem(PurchaseOrderItem ent, String id, UserVo sysUser ) {
        //根据物料编码查询是否存在，不存在就新增
      //  UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        TWhWarehouseCustomerMaterialVo tWhWarehouseCustomerMaterialVo = this.tWhWarehouseCustomerMaterialService.findByMaterialNoAndVehicleModel(ent.getMaterialNo(),ent.getVehicleModel());
        String materialId = "";
        if(tWhWarehouseCustomerMaterialVo==null){
            tWhWarehouseCustomerMaterialVo = new TWhWarehouseCustomerMaterialVo();
            tWhWarehouseCustomerMaterialVo.setMaterialNo(ent.getMaterialNo());
            tWhWarehouseCustomerMaterialVo.setVehicleBrand(ent.getVehicleBrand());
            tWhWarehouseCustomerMaterialVo.setVehicleName(ent.getVehicleName());
            tWhWarehouseCustomerMaterialVo.setVehicleModel(ent.getVehicleModel());
            tWhWarehouseCustomerMaterialVo.setUnitVolume(BigDecimal.valueOf(0));
            tWhWarehouseCustomerMaterialVo.setUnitWeight("0");
            tWhWarehouseCustomerMaterialVo.setCustomerNo("2000");
            tWhWarehouseCustomerMaterialVo.setMeasUnitNo("1");
            TWhWarehouseCustomerMaterialSaveParam t = new TWhWarehouseCustomerMaterialSaveParam();
            org.springframework.beans.BeanUtils.copyProperties(tWhWarehouseCustomerMaterialVo,t);
            this.tWhWarehouseCustomerMaterialService.insert(t);
            materialId = t.getId();
        }else{
            materialId = tWhWarehouseCustomerMaterialVo.getId();
        }

        ent.setMaterialId(materialId);
        ent.setPackQty(BigDecimal.valueOf(1));
        ent.setOrderQuantity(BigDecimal.valueOf(1));
        ent.setMaterialNo(tWhWarehouseCustomerMaterialVo.getMaterialNo());
        ent.setId( idWorker.nextId() + "" ).preInsert(sysUser.getId());
        ent.setIsValid(ApiConstants.Y);
        if(StringUtils.isNull(ent.getShipbyQtyWeightOrPack())){
            ent.setShipbyQtyWeightOrPack("qty");
        }
        ent.setUpdateBy(ent.getCreateBy());
        ent.setPurchaseOrderId(id);
        ent.setSite(ent.getCarrierNo());
        ent.setEstDeliveryTime(ent.getDemandDeliveryDate());
        this.purchaseOrderItemMapper.insert(ent);
    }


    @Override
    @Transactional(readOnly = false)
    public String insertOrder(PurchaseOrderVo dataFromDb,PurchaseOrderItem save, UserVo sysUser ) {
        /*Map<String,Object> map = new HashMap<>();
        List<WarehouseSaveParam> warehouseList = new ArrayList<WarehouseSaveParam>();*/
        //查询提货仓库是否存在

        WarehouseVo wv= warehouseService.findByName(save.getPickUpWarehouseNo());
        String warehouseId = null;
        if(dataFromDb==null){
            dataFromDb = new PurchaseOrderVo();
        }
        String departureName = "山东省/潍坊市/诸城市";
        String departure = "370000,370700,370782";

        String str = save.getCollectionProvince()+"/"+save.getPickupCity()+"/"+save.getCollectionArea();
        TBmLocationVo lvo= locationmapper.findBytreeName(str);

        //提货仓库不存在就新建一个仓库
        if(wv==null){
            WarehouseSaveParam params = new WarehouseSaveParam();
            // remodel 委改厂
            // center 中心库
            // packing 包装库
            String status = null;
            if(save.getPickUpWarehouseNo().indexOf("包装")>-1){
                status = "packing";
            }else if(save.getPickUpWarehouseNo().indexOf("虚拟")>-1){
                status = "virture";
            }else if(save.getPickUpWarehouseNo().indexOf("中心")>-1){
                status = "center";
            }else if(save.getPickUpWarehouseNo().indexOf("委改")>-1){
                status = "remodel";
            }else{
                status = "consignee";
            }
            params.setWarehouserName(save.getPickUpWarehouseNo());
            params.setWarehouserCode(status);
            params.setWarehouseType(status);
            params.setAddress(departureName);
            String [] s = departure.split(",");
            params.setProvince(s[0]);
            params.setCity(s[1]);
            params.setDistrict(s[2]);
            warehouseId = warehouseService.insert(params);
            /*warehouseList.add(params);
            map.put("deliveryWarehouse",warehouseList)*/;
        }else{
            warehouseId = wv.getId();
        }

        //查询卸货虚拟仓库是否存在
        String [] treeids = lvo.getTreeIds().split(",");
        WarehouseVo virtually = warehouseService.findByProvinceAndCityAndDistrict(treeids[0],treeids[1],treeids[2]);
        String dropOffWarehouseNo = "";
        //卸货虚拟仓库不存在，新建一个
        if(virtually==null){
            WarehouseSaveParam w = new WarehouseSaveParam();
            w.setWarehouserName("虚拟仓库");
            w.setWarehouserCode("virtually");
            w.setWarehouseType("virtually");
            w.setAddress(lvo.getTreeNames());
            w.setProvince(treeids[0]);
            w.setCity(treeids[1]);
            w.setDistrict(treeids[2]);
            dropOffWarehouseNo = warehouseService.insert(w);
            /*warehouseList.add(w);
            map.put("virtuallyWarehouse",warehouseList);*/
        }else{
            dropOffWarehouseNo = virtually.getId();
        }

        if(save.getPickUpAddress().contains("诸城市")){
            dataFromDb.setDepartureName(departureName);
            dataFromDb.setDeparture(departure);
        }
        dataFromDb.setDestination(lvo.getTreeIds());
        dataFromDb.setDestinationName(lvo.getTreeNames());
        dataFromDb.setPurchaseOrderNo(save.getPurchaseOrderNo());
        dataFromDb.setCarrier(save.getCarrier());
        dataFromDb.setCarrierNo(save.getCarrierNo());
        dataFromDb.setConsigneeName(save.getContactName());
        dataFromDb.setPickupCity(save.getPickupCity());
        dataFromDb.setPickUpWarehouseNo(warehouseId);
        dataFromDb.setRemark(save.getRemark());
        dataFromDb.setPickupStartDate(save.getPickupStartDate());
        dataFromDb.setExpectReceiptDate(save.getEstPickUpTime());
        dataFromDb.setDropOffWarehouseNo(dropOffWarehouseNo);
        dataFromDb.setCustomerNo("2000");
        dataFromDb.setStatus("planning");
        dataFromDb.setFreightServiceType(save.getServiceType());

        PurchaseOrder po = new PurchaseOrder();
        org.springframework.beans.BeanUtils.copyProperties(dataFromDb,po);

        po.setId( idWorker.nextId() + "" ).preInsert(sysUser.getId());

        this.purchaseOrderMapper.insert(po);
        /*map.put("id",po.getId());
        return map;*/
        return po.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveToExceptions(DispatchImportOrderItemVo data,PurchaseOrderItem ent,UserVo sysUser){
        TbWmsMaterialReceiptNotExist tbWmsMaterialReceiptNotExist = new TbWmsMaterialReceiptNotExist();

        BeanUtils.copyProperties(ent,tbWmsMaterialReceiptNotExist);
        BeanUtils.copyProperties(data,tbWmsMaterialReceiptNotExist);
        tbWmsMaterialReceiptNotExist.setDeliveryNo(data.getPickupVoucherList());
        tbWmsMaterialReceiptNotExist.setVinNo(data.getVinNo());
        tbWmsMaterialReceiptNotExist.setId( idWorker.nextId() + "" ).preInsert(sysUser.getId());

    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public  String importDataWithCarrier(DispatchImportOrderItemVo data,PurchaseOrderItem ent,UserVo sysUser,Integer successNum,Integer failureNum ){
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String rtmsg = "";
       try {
          // PurchaseOrderVo dataFromDb = this.purchaseOrderMapper.findByPurchaseOrderNo(data.getPurchaseOrderNo());
           PurchaseOrderVo dataFromDb = this.purchaseOrderMapper.findbySapDeliveryNo(data.getPickupVoucherList());
           String id = "";
           if (dataFromDb == null) {
               dataFromDb = new PurchaseOrderVo();
               dataFromDb.setPickupVoucherList(data.getPickupVoucherList());
               id = this.insertOrder(dataFromDb, ent, sysUser);
               successMsg.append("<br/>" + successNum + "、发货单 " + data.getPurchaseOrderNo() + " 导入成功");
           } else {
               id = dataFromDb.getId();
           }
           this.insertItem(ent, id, sysUser);
           successNum++;
           rtmsg = successMsg.toString();

       } catch (Exception e) {
        failureNum++;
        String msg = "<br/>" + failureNum + "、订单号 " + data.getPurchaseOrderNo() + " 导入失败：";
        failureMsg.append(msg + e.getMessage());
        log.error(msg, e);
           rtmsg = failureMsg.toString();
      }
        return rtmsg;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public  String importDataWithCarrier2(DispatchImportOrderItemVo data,PurchaseOrderItem ent,UserVo sysUser,String deliveryId){

        PurchaseOrderVo dataFromDb = this.purchaseOrderMapper.findbySapDeliveryNo(data.getPickupVoucherList());
        String id = "";
        if (dataFromDb == null) {
            dataFromDb = new PurchaseOrderVo();
            dataFromDb.setPickupVoucherList(data.getPickupVoucherList());
            dataFromDb.setIsValid("0");
            dataFromDb.setSiteId(deliveryId);
            id = this.insertOrder(dataFromDb, ent, sysUser);
            this.insertItem(ent, id, sysUser);
        }

        return "";
    }

  /*  @Override
    @Transactional(rollbackFor = Exception.class)
    public String importDataWithCarrier(MultipartFile file) {
        List<DispatchImportOrderItemVo> dataList = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        int successNum = 0;
        int failureNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(DispatchImportOrderItemVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }
        for (DispatchImportOrderItemVo data : dataList) {
            try {
                PurchaseOrderItem ent = new PurchaseOrderItem();
                org.springframework.beans.BeanUtils.copyProperties(data, ent);
                ent.setVehicleLoadType(data.getVehicleLoadType());
                ent.setConsigneeName(data.getConsigneeName());*/
                // 验证数据是否存在
           /*     TbWmsMaterialDeliveryLine line = this.tbWmsMaterialDeliveryLineMapper.findBySapOrderNo(data.getPickupVoucherList(),data.getVinNo());
                if(line == null){
                    this.saveToExceptions(data,ent,sysUser);
                    continue;
                }
                PurchaseOrderVo dataFromDb = this.purchaseOrderMapper.findByPurchaseOrderNo(data.getPurchaseOrderNo());
                String id = "";
                if (dataFromDb==null) {*/
                    /*String id = mapper.insert(dataFromDb);*/
                 /*    id = this.insertOrder(dataFromDb,ent,  sysUser );*/
                  //successMsg.append("<br/>" + successNum + "、发货单 " + data.getPurchaseOrderNo() + " 导入成功");
               /*}else{
                    id = dataFromDb.getId();
                }
                this.insertItem(ent,id,sysUser);
                successNum++;*/
                /*else if (isUpdateSupport) {
                    saveParam.setPurchaseOrderId(dataFromDb.getId());
                    this.insertItem(saveParam,dataFromDb.getId());
                    successNum++;*/
                    //successMsg.append("<br/>" + successNum + "、发货单 " + data.getOrderNo() + " 更新成功");
                /*} else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、订单号 " + data.getPurchaseOrderNo() + " 已存在");
                }*/
      /*      } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、订单号 " + data.getPurchaseOrderNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ExcelException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();

    }*/
}
